/*
 * Created by JFormDesigner on Sat Jul 11 21:32:57 CST 2020
 */
package entity.JPanel;

import entity.Model.Books;
import utils.JDBCUtil;

import java.awt.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;

/**
 * @author Brainrain
 */
public class Book_type extends JPanel {
    Connection con;
    ResultSet rs;
    JButton[] b = {new JButton("刷新信息"), new JButton("删除选中行"), new JButton("添加信息")};
    private int rand[] = new int[b.length];
    private Color colors[] = {new Color(238, 130, 238), new Color(123, 104, 238), new Color(0, 191, 255), new Color(255, 140, 0),
            new Color(0, 250, 154), new Color(173, 255, 47), new Color(255, 255, 0), new Color(240, 128, 128), new Color(255, 20, 147)};
    PreparedStatement ps;
    DefaultTableModel tableModel;// 默认显示的表格
    String[] columnNames = {"图书名字", "作者", "类型", "库存","图书书号"}; // 定义表格列名数组
    // 定义表格数据数组
    String[][] tableValues;
    // 创建指定列名和数据的表格
    JTable table;

    public Book_type() {
        initComponents();
    }

    private void initComponents() {
        selectAll();
        setLayout(new BorderLayout());
        //按钮样式:按钮颜色和图标
        setButtonColor();
        setbuttonIcon();
        JPanel jPanel = new JPanel();
        jPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 330, 10));
        for (int i = 0; i < b.length; i++) {
            b[i].setPreferredSize(new Dimension(200, 50));
            jPanel.add(b[i]);
            //按钮失去边框
            b[i].setBorderPainted(false);
            //按钮失去焦点
            b[i].setFocusPainted(false);
            b[i].setFont(new Font("宋体", Font.BOLD, 20));
        }
        b[0].addActionListener((e) -> {
            int rnt = JOptionPane.showConfirmDialog(null, "是否确定刷新", "success", JOptionPane.OK_CANCEL_OPTION);
            if (rnt == JOptionPane.OK_OPTION) {
                refresh();
            }

        });
        b[1].addActionListener((e) -> {
            int rnt = JOptionPane.showConfirmDialog(null, "是否删除", "success", JOptionPane.OK_CANCEL_OPTION);
            if (rnt == JOptionPane.OK_OPTION) {
                delete();
            }
        });
        b[2].addActionListener((e) -> {
            add();
        });
        add(jPanel, BorderLayout.SOUTH);
        tableModel = new DefaultTableModel(tableValues, columnNames);
        table = new JTable(tableModel);
        table.setRowHeight(50);
        table.setFont(new Font("宋体", Font.BOLD, 18));
        table.setBackground(Color.pink);
        //表格内容居中显示
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
        tcr.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, tcr);
        //======表头属性设置====
        table.getTableHeader().setBackground(new Color(0, 191, 255));
        table.getTableHeader().setFont(new Font("楷体", Font.BOLD, 25));
        // 创建显示表格的滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        // 将滚动面板添加到边界布局的中间
        add(scrollPane, BorderLayout.CENTER);
    }

    /**
     * 查询所有图书信息
     */
    public void selectAll() {
        Books books;
        List<Books> list = new ArrayList<>();
        String sql = "select * from books_table";
        try {
            con = JDBCUtil.getConnect();
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                String name = rs.getString("name");
                String author = rs.getString("author");
                String type = rs.getString("type");
                String num = rs.getString("num");
                String id = rs.getString("id");
                books = new Books(name, author, type, num,id);
                list.add(books);
            }
            JDBCUtil.close(ps, rs, con);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        tableValues = new String[list.size()][5];

        System.out.println(list.size());
        for (int k = 0; k < list.size(); k++) {
            tableValues[k][0] = list.get(k).getName();
            tableValues[k][1] = list.get(k).getAuthor();
            tableValues[k][2] = list.get(k).getType();
            tableValues[k][3] = list.get(k).getNum();
            tableValues[k][4] = list.get(k).getId();

        }
    }

    /**
     * 添加一条记录
     */
    public void add() {
        tableModel.addRow(new Vector());
        int column = table.getColumnCount();// 表格列数
        int row = table.getRowCount();// 表格行数
        System.out.println("column:" + column + "row:" + row);
    }

    /**
     * 刷新数据
     */
    public void refresh() {
        int column = table.getColumnCount();// 表格列数
        int row = table.getRowCount();// 表格行数
        String[][] values = new String[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                values[i][j] = table.getValueAt(i,j).toString();
                System.out.print(values[i][j]);
            }
        }
        try {
            con = JDBCUtil.getConnect();
            ps = con.prepareStatement("delete from books_table");
            ps.executeUpdate();//删除表单所有数据
            System.out.println("删除成功" + row);
            for (int i = 0; i < row; i++) {
                System.out.println("刷新成功");
                String sql = "insert into books_table(name,author,type,num,id) values(?,?,?,?,?)";
                ps = con.prepareStatement(sql);
                ps.setString(1, values[i][0]);
                ps.setString(2, values[i][1]);
                ps.setString(3, values[i][2]);
                ps.setString(4, values[i][3]);
                ps.setString(5, values[i][4]);
                ps.executeUpdate();
            }
            JOptionPane.showMessageDialog(null, "刷新成功", "success", JOptionPane.WARNING_MESSAGE);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 删除选中记录
     */
    public void delete() {
        int rowcount = table.getSelectedRow();
        if (rowcount >= 0) {
            tableModel.removeRow(rowcount);
        }
        int column = table.getColumnCount();// 表格列数
        int row = table.getRowCount();// 表格行数
        String[][] values = new String[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                values[i][j] = table.getValueAt(i, j).toString();
                System.out.print(values[i][j]);
            }
        }
        try {
            con = JDBCUtil.getConnect();
            ps = con.prepareStatement("delete from books_table");
            //删除表单所有数据
            ps.executeUpdate();
            System.out.println("删除成功" + row);
            for (int i = 0; i < row; i++) {
                System.out.println("刷新成功");
                String sql = "insert into books_table(name,author,type,num) values(?,?,?,?)";
                ps = con.prepareStatement(sql);
                ps.setString(1, values[i][0]);
                ps.setString(2, values[i][1]);
                ps.setString(3, values[i][2]);
                ps.setString(4, values[i][3]);
                ps.executeUpdate();
            }
            JOptionPane.showMessageDialog(null, "删除成功", "success", JOptionPane.WARNING_MESSAGE);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
        }
    }

    /**
     * 设置按钮样式
     */
    public void setButtonColor() {
        for (int i = 0; i < b.length; i++) {//外循环用于获取随机数0-4
            rand[i] = new Random().nextInt(colors.length);//获取随机数并放入数组中
            for (int j = 0; j < i; j++) {//用于判断是否有相同的随机数
                if (rand[i] == rand[j]) {//若果相同，本次的随机数即从新获取
                    i--;
                    break;
                }
            }
        }
        for (int i = 0; i < rand.length; i++) {
            System.out.println(rand[i]);
            b[i].setBackground(colors[rand[i]]);
        }
    }

    public void setbuttonIcon() {
        b[0].setIcon(new ImageIcon(Book_type.class.getClassLoader().getResource("resources/images/refresh.png").getPath()));
        b[1].setIcon(new ImageIcon(Book_type.class.getClassLoader().getResource("resources/images/delete.png").getPath()));
        b[2].setIcon(new ImageIcon(Book_type.class.getClassLoader().getResource("resources/images/add.png").getPath()));
    }
}
